package priv.lhy.common.utils;

import org.apache.commons.lang3.time.DateUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: lihy
 * date: 2019/6/29 11:33
 * description:
 */
public class DateUtil {

    /**
     * 返回年月
     * @return
     */
    @Deprecated
    public static String getYearAndMonth() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR) + "" + (calendar.get(Calendar.MONTH) + 1);
    }

    /**
     * 返回自定义格式的时间
     * @param date
     * @param format
     * @return
     */
    public static String dateCustomStr(Date date, String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        String time = formatter.format(date);
        return time;
    }

    /**
     * 获取两个时间段之间的每个年月
     * @param begin
     * @param end
     * @return
     * @throws ParseException
     */
    public static List<String> interval(String begin, String end) throws ParseException {
        List<String> interval = new ArrayList<>();

        Calendar beginCal = Calendar.getInstance();
        beginCal.setTime(str2Date(begin, "yyyy-MM"));
        beginCal.set(beginCal.get(Calendar.YEAR), beginCal.get(Calendar.MONTH), 1);

        Calendar endCal = Calendar.getInstance();
        endCal.setTime(str2Date(end, "yyyy-MM"));
        endCal.set(endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH), 2);

        Calendar tempCal = beginCal;
        while (tempCal.before(endCal)){
            interval.add(dateCustomStr(tempCal.getTime(), "yyyyMM"));
            tempCal.add(Calendar.MONTH, 1);
        }

        return interval;
    }

    /***
     * 返回"format格式时间
     *
     * @param dateStr
     * @param format
     * @return
     * @throws ParseException
     */
    public static Date str2Date(String dateStr, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = sdf.parse(dateStr);
        return date;
    }
}
